package com.frog.rss.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.frog.rss.db.RssSQLiteOpenHelper;
import com.frog.rss.domain.RSSItem;

public class RSSItemDao {

	private static RssSQLiteOpenHelper rssSQLiteOpenHelper;
	final static String INSERT_SQL = "insert into "
			+ RssSQLiteOpenHelper.RSS_ITEM_TABLE_NAME
			+ "(title, link, pubDate, description, category, starrted, read) values(?, ?, ?, ?, ?, ?, ?)";
	final static String DELETE_SQL = "delete from "
			+ RssSQLiteOpenHelper.RSS_ITEM_TABLE_NAME + " where id=?";
	final static String LOAD_ALL_RSS_ITEMS_SQL = "select * from "
			+ RssSQLiteOpenHelper.RSS_ITEM_TABLE_NAME;

	public RSSItemDao(Context context) {
		rssSQLiteOpenHelper = new RssSQLiteOpenHelper(context);
	}

	public void insert(RSSItem rssItem) {
		SQLiteDatabase db = rssSQLiteOpenHelper.getWritableDatabase();
		db.execSQL(
				INSERT_SQL,
				new Object[] { rssItem.getTitle(), rssItem.getLink(),
						rssItem.getPubDate(), rssItem.getDescription(),
						rssItem.getCategory(), rssItem.getStarrted(),
						rssItem.getRead() });
		db.close();
	}

	public void delete(int id) {
		SQLiteDatabase db = rssSQLiteOpenHelper.getWritableDatabase();
		db.execSQL(DELETE_SQL, new Object[] { id });
		db.close();
	}

	public List<RSSItem> loadAllRssItems() {
		SQLiteDatabase db = rssSQLiteOpenHelper.getReadableDatabase();
		Cursor cur = db.rawQuery(LOAD_ALL_RSS_ITEMS_SQL, null);
		List<RSSItem> results = new ArrayList<RSSItem>();
		if (cur.moveToFirst()) {
			int titleColumn = cur.getColumnIndex(RSSItem.TITLE);
			int pubDataColumn = cur.getColumnIndex(RSSItem.PUBDATE);
			int linkColumn = cur.getColumnIndex(RSSItem.LINK);
			int descriptionColumn = cur.getColumnIndex(RSSItem.DESCRIPTION);
			int categoryColumn = cur.getColumnIndex(RSSItem.CATEGORY);
			int starredColumn = cur.getColumnIndex(RSSItem.STARRTED);
			int readColumn = cur.getColumnIndex(RSSItem.READ);
			do {
				results.add(new RSSItem(cur.getString(titleColumn), cur
						.getString(linkColumn), cur.getString(pubDataColumn),
						cur.getString(descriptionColumn), cur
								.getString(categoryColumn), cur
								.getInt(starredColumn), cur.getInt(readColumn)));
			} while (cur.moveToNext());
		}
		db.close();
		return results;
	}
}
